package cn.somkit.fmt.config;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import cn.metona.mq.MQToolkit;
import cn.metona.mq.core.MessageQueue;
import cn.somkit.fmt.entity.LoggerMessage;

import java.time.Instant;
import java.time.ZoneId;

public class LogMonitorAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    private static final String Queue_Name = "log-monitor";

    @Override
    protected void append(ILoggingEvent event) {
        LoggerMessage msg = new LoggerMessage(
                event.getLevel().toString(),
                event.getThreadName(),
                event.getLoggerName(),
                event.getFormattedMessage(),
                DateUtil.format(Instant.ofEpochMilli(event.getTimeStamp()).atZone(ZoneId.systemDefault()).toLocalDateTime(),
                        "yyyy-MM-dd HH:mm:ss.SSS"),
                ProcessHandle.current().pid()
        );
        //发送日志信息到日志监控队列
        MessageQueue.QueueStats queueStats = MQToolkit.getQueueStats(Queue_Name);
        if(queueStats != null && queueStats.isRunning() && !queueStats.isPaused()){
            MQToolkit.sendMessage(Queue_Name, "log.monitor", JSONUtil.toJsonStr(msg));
        }
    }
}
